<template>
  <view class="page">
    <!-- 主容器使用flex布局 -->
    <view class="container">
      <!-- 可滚动内容区域 -->
      <scroll-view scroll-y class="scroll-view" enable-back-to-top>
        <view class="cart-header">
          <text class="clear-cart" @click="clearCart">清空购物车</text>
        </view>
        
        <!-- 按店铺分组显示商品 -->
        <view class="store-list">
          <view v-for="(store) in groupedCartItems" :key="store.storeId" class="store-item">
            <!-- 店铺信息 -->
            <view class="store-header">
              <view class="store-select">
                <checkbox :checked="store.isSelected" @click="toggleStoreSelect(store)"/>
                <text class="select-text">全选</text>
              </view>
              <text class="store-name" style="font-size: 32rpx;">{{store.storeName}}</text> <!-- 增大店铺名称字体大小 -->
            </view>
            
            <!-- 店铺商品列表 -->
            <view class="goods-list">
              <view v-for="(item, index) in store.goods" :key="index" class="goods-item">
                <view class="item-left">
                  <checkbox :checked="item.isSelected" @click="toggleSelect(item, store)"/>
                  <image :src="`/static/${item.imgUrl}`" class="goods-image"></image>
                </view>
                
                <view class="item-right">
                  <view class="goods-info">
                    <text class="goods-name" style="font-size: 32rpx;">{{item.name}}</text> <!-- 增大商品名称字体大小 -->
                    <text class="goods-sales">月售{{item.sales}}件</text>
                    <view class="price-box">
                      <text class="current-price">¥{{item.price}}</text>
                      <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                    </view>
                  </view>
                  
                  <view class="stepper">
                    <text class="btn minus" @click="decreaseQuantity(item)">-</text>
                    <text class="number">{{item.quantity}}</text>
                    <text class="btn plus" @click="increaseQuantity(item)">+</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 每个店铺的结算栏 -->
            <view class="store-footer" v-if="store.goods.length > 0">
              <view class="footer-left">
                <text class="total-text">合计：</text>
                <text class="total-price">¥{{getStoreTotal(store).toFixed(2)}}</text>
              </view>
              <button class="submit-btn" @click="handleStoreCheckout(store)">
                去结算({{getStoreSelectedCount(store)}})
              </button>
            </view>
          </view>
        </view>
        
        <!-- 空购物车提示 -->
        <view v-if="totalCount === 0" class="empty-cart">
          <image src="/static/images/empty-cart.png" class="empty-img"></image>
          <text class="empty-text">购物车空空的~~</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupedCartItems: [], 
    };
  },
  
  computed: {
    totalCount() {
      return this.groupedCartItems.reduce((total, store) =>
        total + store.goods.length, 0);
    },
    
    selectedCount() {
      return this.groupedCartItems.reduce((total, store) => 
        total + store.goods.filter(item => item.isSelected).length, 0);
    },
    
    totalPrice() {
      return this.groupedCartItems.reduce((total, store) => {
        return total + store.goods
          .filter(item => item.isSelected)
          .reduce((sum, item) => sum + (item.price * item.quantity), 0);
      }, 0);
    }
  },
  
  onShow() {
    this.loadCartItems();
  },
  
  methods: {
    loadCartItems() {
      const items = uni.getStorageSync('cartItems') || [];
      
      const groupedItems = {};
      items.forEach(item => {
        if (!groupedItems[item.storeId]) {
          groupedItems[item.storeId] = {
            storeId: item.storeId,
            storeName: item.storeName,
            isSelected: false,
            goods: []
          };
        }
        groupedItems[item.storeId].goods.push({
          ...item,
          isSelected: item.isSelected || false
        });
      });
      
      this.groupedCartItems = Object.values(groupedItems);
    },
    
    toggleSelect(item, store) {
      item.isSelected = !item.isSelected;
      store.isSelected = store.goods.every(item => item.isSelected);
      this.updateCart();
    },
    
    toggleStoreSelect(store) {
      store.isSelected = !store.isSelected;
      store.goods.forEach(item => {
        item.isSelected = store.isSelected;
      });
      this.updateCart();
    },
    
    updateCart() {
      const flatItems = this.groupedCartItems.reduce((items, store) => {
        return items.concat(store.goods);
      }, []);
      uni.setStorageSync('cartItems', flatItems);
    },
    
    increaseQuantity(item) {
      item.quantity++;
      this.updateCart();
    },
    
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
      } else {
        this.removeItem(item);
      }
      this.updateCart();
    },
    
    removeItem(item) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            const index = this.groupedCartItems.findIndex(store => 
              store.goods.some(i => i._id === item._id));
            if (index !== -1) {
              const store = this.groupedCartItems[index];
              const goodsIndex = store.goods.findIndex(i => i._id === item._id);
              if (goodsIndex !== -1) {
                store.goods.splice(goodsIndex, 1);
              }
              this.updateCart();
            }
          }
        }
      });
    },
    
    clearCart() {
      if (this.totalCount === 0) return;
      
      uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
          if (res.confirm) {
            this.groupedCartItems = [];
            uni.removeStorageSync('cartItems');
          }
        }
      });
    },
    
    getStoreSelectedCount(store) {
      return store.goods.filter(item => item.isSelected).length;
    },
    
    getStoreTotal(store) {
      return store.goods
        .filter(item => item.isSelected)
        .reduce((total, item) => total + (item.price * item.quantity), 0);
    },
    
    handleStoreCheckout(store) {
      const selectedCount = this.getStoreSelectedCount(store);
      if (selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }
      
      const selectedItems = store.goods.filter(item => item.isSelected);
      uni.setStorageSync('selectedCartItems', selectedItems);
      
      uni.switchTab({
        url: '/pages/order/order'
      });
    },
  }
};
</script>

<style scoped>
/* 基础样式 */
page {
  height: 100%;
  background-color: #f7f7f7;
}

.page {
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.scroll-view {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
}

/* 头部样式 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  font-size: 28rpx;
}

.clear-cart {
  color: #666;
}

/* 商品列表样式 */
.goods-list {
  padding-bottom: 20rpx;
}

.goods-item {
  display: flex;
  padding: 25rpx 20rpx;
  margin-bottom: 10rpx;
  background-color: #fff;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  border-radius: 10rpx; /* 添加圆角 */
}

.item-left {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.goods-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx; /* 商品图片添加圆角 */
  margin-left: 15rpx;
}

.item-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-info {
  flex: 1;
}

.goods-name {
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-sales {
  font-size: 26rpx; /* 稍微增大商品销量字体大小 */
  color: #999;
  margin: 8rpx 0;
}

.price-box {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 34rpx; /* 增大当前价格字体大小 */
  color: #e74c3c;
  font-weight: bold;
}

.original-price {
  font-size: 26rpx; /* 增大原价字体大小 */
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}

/* 数量加减器 */
.stepper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx; /* 增大加减按钮字体大小 */
}

.minus {
  background-color: #f5f5f5;
}

.plus {
  background-color: #1b76f6;
  color: #fff;
}

.number {
  margin: 0 20rpx;
  font-size: 32rpx; /* 增大数量数字字体大小 */
  min-width: 40rpx;
  text-align: center;
}

/* 空购物车样式 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 100rpx;
}

.empty-img {
  width: 350rpx;
  height: 350rpx; /* 增大空购物车图片大小 */
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx; /* 增大空购物车提示文字字体大小 */
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1b76f6;
  color: white;
  font-size: 30rpx;
  border-radius: 40rpx;
}

/* 底部结算栏 - 关键样式 */
.footer-bar {
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
  z-index: 100;
}

.footer-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.select-text {
  margin: 0 15rpx 0 10rpx;
  font-size: 30rpx; /* 增大全选文字字体大小 */
}

.total-text {
  font-size: 30rpx; /* 增大合计文字字体大小 */
  color: #333;
}

.total-price {
  font-size: 36rpx; /* 增大合计价格字体大小 */
  color: #e74c3c;
  font-weight: bold;
  margin-left: 10rpx;
}

.submit-btn {
  width: 220rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1b76f6;
  color: white;
  font-size: 30rpx;
  border-radius: 40rpx;
  margin: 0;
  padding: 0;
}

/* 添加店铺相关样式 */
.store-list {
  margin-bottom: 20rpx;
}

.store-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1); /* 店铺容器添加阴影效果 */
  border-radius: 10rpx; /* 店铺容器添加圆角 */
}

.store-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.store-select {
  display: flex;
  align-items: center;
}

.select-text {
  font-size: 30rpx;
  color: #333;
  margin-left: 10rpx;
}

.store-name {
  font-weight: bold;
}

/* 店铺结算栏样式 */
.store-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #f5f5f5;
  border-bottom-left-radius: 10rpx; /* 店铺结算栏添加底部圆角 */
  border-bottom-right-radius: 10rpx;
}
</style>    